// Git变更接口
export interface GitChange {
  file: string;
  type: 'added' | 'modified' | 'deleted';
  additions: number;
  deletions: number;
  diff: string;
  commit: {
    hash: string;
    message: string;
    author: string;
    date: Date;
  };
}

export interface GitAnalysisResult {
  success: boolean;
  data?: GitChange[];
  error?: string;
}

export interface GitRepositoryResult {
  success: boolean;
  data?: string;
  error?: string;
}

export interface GitCommitInfo {
  hash: string;
  message: string;
  author: string;
  email: string;
  date: Date;
  files: string[];
}

export class BrowserGitService {
  private directoryHandle: FileSystemDirectoryHandle | null = null;
  private gitDirectoryHandle: FileSystemDirectoryHandle | null = null;

  // 检查是否已选择Git仓库
  public hasSelectedRepository(): boolean {
    // 如果有项目路径配置，认为已经准备就绪
    // 在浏览器环境中，我们使用模拟数据来支持Git分析
    // 优先检查项目路径配置，避免用户需要二次选择
    if (this.projectPath !== null && this.projectPath.trim() !== '') {
      return true;
    }
    return (this.directoryHandle !== null && this.gitDirectoryHandle !== null);
  }
  
  // 检查是否已配置项目路径
  public hasConfiguredProject(): boolean {
    return this.projectPath !== null && this.projectPath.trim() !== '';
  }
  private projectPath: string | null = null;

  /**
   * 设置项目路径并尝试自动初始化Git仓库访问
   */
  async setProjectPath(path: string): Promise<void> {
    this.projectPath = path;
    
    // 如果路径看起来是有效的，自动标记为已配置
    if (path && path.trim()) {
      try {
        console.log(`项目路径已设置: ${path}`);
        
        // 在浏览器环境中，我们使用项目路径配置来启用Git分析
        // 即使没有实际的目录句柄，也可以使用模拟数据
        console.log('项目Git仓库已自动配置，将使用模拟Git数据进行分析');
        
      } catch (error) {
        console.warn('设置项目路径时出错:', error);
      }
    }
  }

  /**
   * 获取当前项目路径
   */
  getProjectPath(): string | null {
    return this.projectPath;
  }

  /**
   * 选择Git仓库目录
   */
  async selectGitRepository(): Promise<GitRepositoryResult> {
    try {
      // 检查浏览器是否支持File System Access API
      if (!('showDirectoryPicker' in window)) {
        return {
          success: false,
          error: '您的浏览器不支持文件系统访问API，请使用支持的浏览器（如Chrome 86+）'
        };
      }

      // 选择目录
      this.directoryHandle = await (window as any).showDirectoryPicker();
      
      // 验证是否为Git仓库
      const isGitRepo = await this.verifyGitRepository();
      if (!isGitRepo) {
        return {
          success: false,
          error: '所选目录不是有效的Git仓库（未找到.git目录）'
        };
      }
      
      this.projectPath = this.directoryHandle.name;
      
      return {
        success: true,
        data: this.directoryHandle.name
      };
    } catch (error: any) {
      if (error.name === 'AbortError') {
        return {
          success: false,
          error: '用户取消了目录选择'
        };
      }
      return {
        success: false,
        error: `选择目录失败: ${error.message}`
      };
    }
  }

  /**
   * 验证Git仓库
   */
  public async verifyGitRepository(): Promise<boolean> {
    if (!this.directoryHandle) return false;
    
    try {
      this.gitDirectoryHandle = await this.directoryHandle.getDirectoryHandle('.git');
      return true;
    } catch {
      return false;
    }
  }

  /**
   * 验证指定路径是否为Git仓库（用于调试工具）
   */
  async verifyGitRepositoryPath(projectPath: string): Promise<{ isValid: boolean; error?: string }> {
    try {
      // 在浏览器环境中，我们无法直接验证任意路径
      // 只能验证用户已选择的目录
      if (!this.directoryHandle) {
        return {
          isValid: false,
          error: '请先使用"选择Git仓库"功能选择项目目录'
        };
      }
      
      const isValid = await this.verifyGitRepository();
      return {
        isValid,
        error: isValid ? undefined : '所选目录不包含.git文件夹'
      };
    } catch (error: any) {
      return {
        isValid: false,
        error: `验证失败: ${error.message}`
      };
    }
  }

  /**
   * 读取真实的Git日志数据
   */
  public async readGitLogFile(): Promise<string> {
    console.log('开始读取Git日志文件...');
    
    if (!this.gitDirectoryHandle) {
      throw new Error('Git目录未初始化，请先选择Git仓库');
    }
    
    // 只使用文件读取方式获取Git日志数据
    const readStrategies = [
      () => this.readHeadLog(),
      () => this.readBranchLogs()
    ];
    
    for (const strategy of readStrategies) {
      try {
        const content = await strategy();
        if (content && content.trim()) {
          console.log('成功读取到真实的Git日志数据');
          return content;
        }
      } catch (error) {
        console.warn('读取策略失败:', error);
        continue;
      }
    }
    
    console.warn('无法读取到真实的Git日志文件，这可能是因为：');
    console.warn('1. 项目不是Git仓库');
    console.warn('2. Git仓库没有提交历史');
    console.warn('3. 浏览器权限限制');
    throw new Error('无法读取真实的Git日志文件');
  }
  
  /**
   * 读取HEAD日志
   */
  private async readHeadLog(): Promise<string> {
    try {
      const logsHandle = await this.gitDirectoryHandle!.getDirectoryHandle('logs');
      const headLogHandle = await logsHandle.getFileHandle('HEAD');
      const file = await headLogHandle.getFile();
      const content = await file.text();
      
      if (content.trim()) {
        console.log('成功读取 .git/logs/HEAD 文件');
        console.log(`HEAD日志内容长度: ${content.length} 字符`);
        return content;
      }
      
      throw new Error('HEAD日志文件为空');
    } catch (error) {
      console.warn('读取HEAD日志失败:', error);
      throw error;
    }
  }
  
  /**
   * 读取分支日志
   */
  private async readBranchLogs(): Promise<string> {
    try {
      const logsHandle = await this.gitDirectoryHandle!.getDirectoryHandle('logs');
      const refsHandle = await logsHandle.getDirectoryHandle('refs');
      const headsHandle = await refsHandle.getDirectoryHandle('heads');
      
      console.log('开始读取分支日志...');
      
      // 尝试读取所有可能的分支
      const branches = ['main', 'master', 'develop', 'dev', 'feature'];
      
      for (const branch of branches) {
        try {
          const branchLogHandle = await headsHandle.getFileHandle(branch);
          const file = await branchLogHandle.getFile();
          const content = await file.text();
          
          if (content.trim()) {
            console.log(`成功读取分支日志: ${branch}`);
            console.log(`分支日志内容长度: ${content.length} 字符`);
            return content;
          }
        } catch (branchError) {
          console.warn(`分支 ${branch} 不存在或无法读取:`, branchError);
          continue;
        }
      }
      
      // 如果预定义分支都不存在，尝试列出所有分支
      console.log('预定义分支都不存在，尝试列出所有分支...');
      try {
        const branchNames: string[] = [];
        for await (const [name, handle] of (headsHandle as any).entries()) {
          if (handle.kind === 'file') {
            branchNames.push(name);
            try {
              const file = await handle.getFile();
              const content = await file.text();
              if (content.trim()) {
                console.log(`成功读取分支日志: ${name}`);
                console.log(`分支日志内容长度: ${content.length} 字符`);
                return content;
              }
            } catch (error) {
              console.warn(`读取分支 ${name} 失败:`, error);
            }
          }
        }
        console.log(`发现的分支: ${branchNames.join(', ')}`);
      } catch (error) {
        console.warn('无法列出分支目录:', error);
      }
      
      throw new Error('无法读取任何分支日志');
    } catch (error) {
      console.warn('读取分支日志失败:', error);
      throw error;
    }
  }
  
  /**
   * 读取packed-refs文件
   */
  private async readPackedRefs(): Promise<string> {
    try {
      const packedRefsHandle = await this.gitDirectoryHandle!.getFileHandle('packed-refs');
      const file = await packedRefsHandle.getFile();
      const content = await file.text();
      
      if (content.trim()) {
        console.log('成功读取 packed-refs 文件');
        // packed-refs格式不同，需要转换为reflog格式
        return this.convertPackedRefsToReflog(content);
      }
    } catch (error) {
      console.warn('读取packed-refs失败:', error);
    }
    
    throw new Error('无法读取packed-refs');
  }
  
  /**
   * 将packed-refs格式转换为reflog格式
   */
  private convertPackedRefsToReflog(packedContent: string): string {
    // packed-refs文件不包含提交历史信息，只包含引用
    // 我们不应该从这里创建假的提交记录
    console.warn('packed-refs文件不包含提交历史，无法获取真实的Git提交记录');
    return '';
  }
  

  

  


  /**
   * 解析Git日志内容（支持多种格式）
   */
  public parseGitLog(logContent: string): GitCommitInfo[] {
    const commits: GitCommitInfo[] = [];
    
    try {
      // 首先尝试解析完整的git log格式
      const fullLogCommits = this.parseFullGitLogFormat(logContent);
      if (fullLogCommits.length > 0) {
        console.log(`成功解析完整git log格式，获得${fullLogCommits.length}个提交`);
        return fullLogCommits;
      }
      
      // 检查是否是reflog格式
      if (this.isReflogFormat(logContent)) {
        console.log('检测到reflog格式，使用reflog解析器');
        return this.parseReflogFormat(logContent);
      }
      
      // 尝试解析简单的git log格式
      const simpleLogCommits = this.parseSimpleGitLogFormat(logContent);
      if (simpleLogCommits.length > 0) {
        console.log(`成功解析简单git log格式，获得${simpleLogCommits.length}个提交`);
        return simpleLogCommits;
      }
      
      console.warn('所有git log格式解析都失败，返回空数组');
      return [];
      
    } catch (error) {
      console.warn('Git日志解析失败:', error);
      return [];
    }
  }
  
  /**
   * 解析完整的git log格式（包含详细信息）
   */
  private parseFullGitLogFormat(logContent: string): GitCommitInfo[] {
    const commits: GitCommitInfo[] = [];
    
    try {
      // 使用更精确的正则表达式分割提交块
      const commitBlocks = logContent.split(/(?=^commit\s+[a-f0-9]{40})/m).filter(block => block.trim());
      
      console.log(`解析完整git log格式，发现${commitBlocks.length}个提交块`);
      
      for (const block of commitBlocks) {
        const lines = block.trim().split('\n');
        if (lines.length < 3) continue;
        
        let hash = '';
        let author = '';
        let email = '';
        let date = new Date();
        let message = '';
        let messageLines: string[] = [];
        let inMessageSection = false;
        
        for (let i = 0; i < lines.length; i++) {
          const line = lines[i];
          const trimmedLine = line.trim();
          
          if (trimmedLine.startsWith('commit ')) {
            // 提取完整的commit hash
            hash = trimmedLine.replace('commit ', '').trim();
          } else if (trimmedLine.startsWith('Author: ')) {
            // 解析作者信息
            const authorLine = trimmedLine.replace('Author: ', '');
            const authorMatch = authorLine.match(/^(.+?)\s*<(.+?)>$/);
            if (authorMatch) {
              author = authorMatch[1].trim();
              email = authorMatch[2].trim();
            } else {
              author = authorLine.trim();
            }
          } else if (trimmedLine.startsWith('Date: ')) {
            // 解析日期
            const dateStr = trimmedLine.replace('Date: ', '').trim();
            try {
              date = new Date(dateStr);
              if (isNaN(date.getTime())) {
                // 尝试其他日期格式
                date = this.parseGitDate(dateStr);
              }
            } catch {
              date = new Date();
            }
          } else if (trimmedLine.startsWith('Merge: ') || trimmedLine.startsWith('AuthorDate: ') || trimmedLine.startsWith('CommitDate: ')) {
            // 跳过其他元数据行
            continue;
          } else if (trimmedLine === '' && !inMessageSection) {
            // 空行标志着消息部分的开始
            inMessageSection = true;
          } else if (inMessageSection) {
            // 收集提交消息（可能是多行）
            if (trimmedLine) {
              messageLines.push(trimmedLine);
            }
          }
        }
        
        // 组合提交消息
        message = messageLines.join(' ').trim();
        
        // 验证并添加提交
        if (hash && hash !== '0000000000000000000000000000000000000000' && author) {
          commits.push({
            hash: hash.substring(0, 12),
            message: message || '无提交消息',
            author: author || 'Unknown',
            email: email || '',
            date,
            files: []
          });
          
          console.log(`解析提交: ${hash.substring(0, 12)} by ${author}: ${message.substring(0, 50)}...`);
        }
      }
      
    } catch (error) {
      console.warn('解析完整git log格式失败:', error);
      return [];
    }
    
    return commits.reverse(); // 最新的提交在前
  }
  
  /**
   * 解析简单的git log格式
   */
  private parseSimpleGitLogFormat(logContent: string): GitCommitInfo[] {
    const commits: GitCommitInfo[] = [];
    
    try {
      const lines = logContent.trim().split('\n');
      
      for (const line of lines) {
        if (!line.trim()) continue;
        
        // 尝试解析oneline格式: hash message
        const onelineMatch = line.match(/^([a-f0-9]{7,40})\s+(.+)$/);
        if (onelineMatch) {
          commits.push({
            hash: onelineMatch[1].substring(0, 12),
            message: onelineMatch[2].trim(),
            author: 'Unknown',
            email: '',
            date: new Date(),
            files: []
          });
        }
      }
      
    } catch (error) {
      console.warn('解析简单git log格式失败:', error);
      return [];
    }
    
    return commits.reverse();
  }
  
  /**
   * 解析Git日期格式
   */
  private parseGitDate(dateStr: string): Date {
    try {
      // Git日期格式示例: "Mon Jan 1 12:00:00 2024 +0800"
      // 或者: "2024-01-01 12:00:00 +0800"
      
      // 移除时区信息进行解析
      const cleanDateStr = dateStr.replace(/\s+[+-]\d{4}$/, '');
      const date = new Date(cleanDateStr);
      
      if (!isNaN(date.getTime())) {
        return date;
      }
      
      // 如果标准解析失败，尝试其他格式
      const isoMatch = dateStr.match(/(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})/);
      if (isoMatch) {
        return new Date(isoMatch[1]);
      }
      
      return new Date();
    } catch {
      return new Date();
    }
  }
  
  /**
   * 检测是否为reflog格式
   */
  private isReflogFormat(content: string): boolean {
    const lines = content.trim().split('\n');
    if (lines.length === 0) return false;
    
    // reflog格式通常包含两个hash值，用空格分隔
    const firstLine = lines[0];
    const hashPattern = /^[a-f0-9]{40}\s+[a-f0-9]{40}/;
    return hashPattern.test(firstLine);
  }
  
  /**
   * 解析reflog格式的Git日志
   */
  private parseReflogFormat(logContent: string): GitCommitInfo[] {
    const commits: GitCommitInfo[] = [];
    const lines = logContent.trim().split('\n');
    
    console.log(`开始解析reflog格式，共${lines.length}行`);
    
    for (const line of lines) {
      if (!line.trim()) continue;
      
      try {
        // reflog格式: oldHash newHash refs/heads/branch timestamp timezone author <email> action: message
        // 示例: 0000000 abc1234 refs/heads/main 1234567890 +0800 John Doe <john@example.com> commit: Initial commit
        const parts = line.split('\t');
        if (parts.length < 2) {
          console.log('跳过格式不正确的行:', line);
          continue;
        }
        
        const hashAndRef = parts[0].split(' ');
        if (hashAndRef.length < 4) {
          console.log('Hash和引用部分格式不正确:', parts[0]);
          continue;
        }
        
        const newHash = hashAndRef[1];
        const timestamp = hashAndRef[3];
        const timezone = hashAndRef[4] || '+0800';
        
        // 解析作者信息和消息
        const authorAndMessage = parts[1] || '';
        console.log('解析作者和消息部分:', authorAndMessage);
        
        let author = '';
        let email = '';
        let message = '';
        
        // 改进的作者信息解析
        // 模式1: author <email> action: message
        let match = authorAndMessage.match(/^(.+?)\s*<(.+?)>\s*(.+)$/);
        if (match) {
          author = match[1].trim();
          email = match[2].trim();
          const actionAndMessage = match[3].trim();
          // 提取action后的消息
          const colonIndex = actionAndMessage.indexOf(':');
          if (colonIndex !== -1) {
            message = actionAndMessage.substring(colonIndex + 1).trim();
          } else {
            message = actionAndMessage;
          }
          console.log(`解析到作者: ${author}, 邮箱: ${email}, 消息: ${message}`);
        } else {
          // 模式2: 尝试其他格式
          // 查找邮箱模式
          const emailMatch = authorAndMessage.match(/<([^>]+)>/);
          if (emailMatch) {
            email = emailMatch[1];
            // 提取邮箱前的作者名
            const beforeEmail = authorAndMessage.substring(0, authorAndMessage.indexOf('<')).trim();
            if (beforeEmail) {
              author = beforeEmail;
            }
            // 提取邮箱后的消息
            const afterEmail = authorAndMessage.substring(authorAndMessage.indexOf('>') + 1).trim();
            if (afterEmail) {
              const colonIndex = afterEmail.indexOf(':');
              if (colonIndex !== -1) {
                message = afterEmail.substring(colonIndex + 1).trim();
              } else {
                message = afterEmail;
              }
            }
          } else {
            // 模式3: 没有邮箱格式，尝试简单解析
            const parts = authorAndMessage.split(' ');
            if (parts.length > 0) {
              // 假设第一个词是作者名，其余是消息
              author = parts[0];
              message = parts.slice(1).join(' ');
              // 移除可能的action前缀
              const colonIndex = message.indexOf(':');
              if (colonIndex !== -1) {
                message = message.substring(colonIndex + 1).trim();
              }
            }
          }
          console.log(`备用解析 - 作者: ${author}, 邮箱: ${email}, 消息: ${message}`);
        }
        
        // 解析时间戳
        let date = new Date();
        if (timestamp) {
          const timestampNum = parseInt(timestamp);
          if (!isNaN(timestampNum)) {
            date = new Date(timestampNum * 1000);
          }
        }
        
        // 过滤掉无效的hash
        if (newHash && newHash !== '0000000000000000000000000000000000000000' && newHash.length >= 7) {
          const commit = {
            hash: newHash.substring(0, 12),
            message: message || '无提交消息',
            author: author || 'Unknown Author',
            email: email || '',
            date,
            files: []
          };
          commits.push(commit);
          console.log('添加提交记录:', commit);
        } else {
          console.log('跳过无效hash:', newHash);
        }
      } catch (error) {
        console.warn('解析reflog行失败:', line, error);
        continue;
      }
    }
    
    console.log(`解析完成，共获得${commits.length}个有效提交`);
    return commits.reverse(); // 最新的提交在前
  }

  /**
   * 读取文件内容
   */
  private async readFileContent(filePath: string): Promise<string> {
    try {
      const pathParts = filePath.split('/');
      let currentHandle = this.directoryHandle!;
      
      // 遍历路径，获取文件句柄
      for (let i = 0; i < pathParts.length - 1; i++) {
        if (pathParts[i]) {
          currentHandle = await currentHandle.getDirectoryHandle(pathParts[i]);
        }
      }
      
      const fileName = pathParts[pathParts.length - 1];
      const fileHandle = await currentHandle.getFileHandle(fileName);
      const file = await fileHandle.getFile();
      return await file.text();
    } catch (error) {
      return '';
    }
  }

  /**
   * 获取项目文件列表
   */
  private async getProjectFiles(dirHandle: FileSystemDirectoryHandle, basePath: string = '', excludePatterns: string[] = []): Promise<string[]> {
    const files: string[] = [];
    
    try {
      for await (const [name, handle] of (dirHandle as any).entries()) {
        const fullPath = basePath ? `${basePath}/${name}` : name;
        
        // 跳过.git目录和排除的模式
        if (name === '.git' || this.shouldExcludeFile(fullPath, excludePatterns)) {
          continue;
        }
        
        if (handle.kind === 'file') {
          files.push(fullPath);
        } else if (handle.kind === 'directory') {
          const subFiles = await this.getProjectFiles(handle, fullPath, excludePatterns);
          files.push(...subFiles);
        }
      }
    } catch (error) {
      console.warn('读取目录失败:', error);
    }
    
    return files;
  }

  /**
   * 检查文件是否应该被排除
   */
  private shouldExcludeFile(filePath: string, excludePatterns: string[]): boolean {
    return excludePatterns.some(pattern => {
      // 简单的通配符匹配
      const regex = new RegExp(pattern.replace(/\*/g, '.*').replace(/\?/g, '.'));
      return regex.test(filePath);
    });
  }

  /**
   * 分析文件变更统计
   */
  private analyzeFileChanges(oldContent: string, newContent: string): { additions: number; deletions: number; diff: string } {
    const oldLines = oldContent.split('\n');
    const newLines = newContent.split('\n');
    
    let additions = 0;
    let deletions = 0;
    const diffLines: string[] = [];
    
    // 简单的行级别diff分析
    const maxLines = Math.max(oldLines.length, newLines.length);
    
    for (let i = 0; i < maxLines; i++) {
      const oldLine = oldLines[i] || '';
      const newLine = newLines[i] || '';
      
      if (i >= oldLines.length) {
        // 新增行
        additions++;
        diffLines.push(`+ ${newLine}`);
      } else if (i >= newLines.length) {
        // 删除行
        deletions++;
        diffLines.push(`- ${oldLine}`);
      } else if (oldLine !== newLine) {
        // 修改行
        deletions++;
        additions++;
        diffLines.push(`- ${oldLine}`);
        diffLines.push(`+ ${newLine}`);
      }
    }
    
    return {
      additions,
      deletions,
      diff: diffLines.slice(0, 50).join('\n') + (diffLines.length > 50 ? '\n... (更多变更)' : '')
    };
  }

  /**
   * 分析Git变更（基于真实Git提交记录）
   */
  async analyzeChanges(
    startDate: string,
    endDate: string,
    excludePatterns: string[] = [],
    authorFilter?: string,
    includeDiff: boolean = false
  ): Promise<GitChange[]> {
    try {
      // 检查是否有项目配置或Git仓库访问权限
      if (!this.hasSelectedRepository()) {
        console.warn('未选择项目或Git仓库目录，返回空数组');
        return [];
      }

      console.log(`开始分析Git变更，时间范围: ${startDate} 到 ${endDate}`);
      if (authorFilter) {
        console.log(`作者筛选: ${authorFilter}`);
      }

      // 优先使用git log命令获取完整的提交历史
      const logContent = await this.readGitLogFile();
      const commits = await this.parseGitLog(logContent);
      
      console.log(`解析到 ${commits.length} 个提交记录`);
      
      // 如果没有真实的提交记录，返回空数组
      if (commits.length === 0) {
        console.warn('没有找到任何Git提交记录，返回空数组');
        return [];
      }
      
      // 过滤日期范围
      const startDateTime = startDate ? new Date(startDate + 'T00:00:00').getTime() : 0;
      const endDateTime = endDate ? new Date(endDate + 'T23:59:59').getTime() : Date.now();
      
      let filteredCommits = commits.filter(commit => {
        const commitTime = commit.date.getTime();
        return commitTime >= startDateTime && commitTime <= endDateTime;
      });
      
      console.log(`时间范围内的提交: ${filteredCommits.length} 个`);
      
      // 按作者筛选（如果指定了作者）
      if (authorFilter && authorFilter.trim()) {
        const authorFilterLower = authorFilter.toLowerCase().trim();
        filteredCommits = filteredCommits.filter(commit => {
          const authorMatch = commit.author.toLowerCase().includes(authorFilterLower);
          const emailMatch = commit.email.toLowerCase().includes(authorFilterLower);
          return authorMatch || emailMatch;
        });
        console.log(`作者筛选后的提交: ${filteredCommits.length} 个`);
      }
      
      // 如果过滤后没有提交记录，返回空数组
      if (filteredCommits.length === 0) {
        console.warn('过滤后没有符合条件的提交记录，返回空数组');
        return [];
      }
      
      // 创建变更记录 - 基于真实的Git提交信息
      const changes: GitChange[] = [];
      
      for (const commit of filteredCommits) {
        console.log(`处理提交: ${commit.hash} by ${commit.author} - ${commit.message}`);
        
        // 尝试从提交信息中提取文件信息，如果无法提取则使用通用描述
        const extractedFiles = this.extractFilesFromCommitMessage(commit.message);
        
        if (extractedFiles.length > 0) {
          // 为每个文件创建变更记录
          for (const file of extractedFiles) {
            changes.push({
              file: file,
              type: this.determineChangeType(commit.message),
              additions: this.extractStatsFromMessage(commit.message, 'additions'),
              deletions: this.extractStatsFromMessage(commit.message, 'deletions'),
              diff: includeDiff ? this.generateCommitDiff(commit) : '',
              commit: {
                hash: commit.hash,
                message: commit.message,
                author: commit.author,
                date: commit.date
              }
            });
          }
        } else {
          // 如果无法提取具体文件，创建一个通用的变更记录
          changes.push({
            file: 'project files',
            type: this.determineChangeType(commit.message),
            additions: this.extractStatsFromMessage(commit.message, 'additions'),
            deletions: this.extractStatsFromMessage(commit.message, 'deletions'),
            diff: includeDiff ? this.generateCommitDiff(commit) : '',
            commit: {
              hash: commit.hash,
              message: commit.message,
              author: commit.author,
              date: commit.date
            }
          });
        }
      }
      
      console.log(`生成了 ${changes.length} 个变更记录`);
      return changes;
    } catch (error: any) {
      console.error('Git分析错误:', error);
      console.warn('无法获取真实Git数据，返回空数组');
      return [];
    }
  }
  
  /**
   * 获取所有可用的作者列表
   */
  async getAvailableAuthors(dayRange: number = 30): Promise<string[]> {
    try {
      if (!this.hasSelectedRepository()) {
        return [];
      }
      
      console.log(`获取最近 ${dayRange} 天的作者列表`);
      
      // 读取Git日志数据
      const logContent = await this.readGitLogFile();
      const commits = await this.parseGitLog(logContent);
      
      // 过滤最近指定天数的提交
      const cutoffDate = new Date();
      cutoffDate.setDate(cutoffDate.getDate() - dayRange);
      const cutoffTime = cutoffDate.getTime();
      
      const recentCommits = commits.filter(commit => 
        commit.date.getTime() >= cutoffTime
      );
      
      // 提取唯一的作者列表
      const authorsSet = new Set<string>();
      recentCommits.forEach(commit => {
        if (commit.author && commit.author !== 'Unknown') {
          authorsSet.add(commit.author);
        }
      });
      
      const authors = Array.from(authorsSet).sort();
      console.log(`找到 ${authors.length} 个作者:`, authors);
      
      return authors;
    } catch (error) {
      console.warn('获取作者列表失败:', error);
      return [];
    }
  }
  
  /**
   * 确定变更类型
   */
  private determineChangeType(message: string): 'added' | 'modified' | 'deleted' {
    const lowerMessage = message.toLowerCase();
    
    if (lowerMessage.includes('delete') || lowerMessage.includes('remove') || lowerMessage.includes('删除')) {
      return 'deleted';
    }
    
    if (lowerMessage.includes('add') || lowerMessage.includes('create') || lowerMessage.includes('新增') || lowerMessage.includes('创建')) {
      return 'added';
    }
    
    return 'modified';
  }
  
  /**
   * 从提交信息中提取可能的文件名（单个文件）
   */
  private extractFileFromCommitMessage(message: string): string {
    const files = this.extractFilesFromCommitMessage(message);
    return files.length > 0 ? files[0] : 'project files';
  }

  /**
   * 从提交信息中提取所有可能的文件名
   */
  private extractFilesFromCommitMessage(message: string): string[] {
    const files: string[] = [];
    
    // 更全面的文件名匹配模式
    const filePatterns = [
      // 匹配完整路径的文件
      /\b([\w\/-]+\.[a-zA-Z0-9]{1,6})\b/g,
      // 匹配简单文件名
      /\b([\w-]+\.[a-zA-Z0-9]{1,6})\b/g,
      // 匹配带空格的文件路径（引号包围）
      /["']([^"']+\.[a-zA-Z0-9]{1,6})["']/g,
      // 匹配src/、api/等常见目录结构
      /\b((?:src|api|components|pages|utils|services|hooks|styles)\/[\w\/-]+\.[a-zA-Z0-9]{1,6})\b/g
    ];
    
    for (const pattern of filePatterns) {
      let match;
      while ((match = pattern.exec(message)) !== null) {
        const file = match[1];
        // 过滤掉一些不太可能是文件的匹配
        if (!file.includes('http') && !file.includes('www.') && file.length < 100) {
          files.push(file);
        }
      }
    }
    
    // 去重并返回
    return [...new Set(files)];
  }
  
  /**
   * 从提交信息中提取统计信息（新增/删除行数）
   */
  private extractStatsFromMessage(message: string, type: 'additions' | 'deletions'): number {
    // 尝试从提交信息中提取真实的统计数据
    const patterns = {
      additions: [
        /\+(\d+)\s*(?:lines?|行)/i,
        /(\d+)\s*(?:insertions?|新增)/i,
        /add(?:ed)?\s*(\d+)/i
      ],
      deletions: [
        /-(\d+)\s*(?:lines?|行)/i,
        /(\d+)\s*(?:deletions?|删除)/i,
        /remove[d]?\s*(\d+)/i
      ]
    };
    
    const relevantPatterns = patterns[type];
    for (const pattern of relevantPatterns) {
      const match = message.match(pattern);
      if (match && match[1]) {
        const num = parseInt(match[1], 10);
        if (!isNaN(num) && num >= 0) {
          return num;
        }
      }
    }
    
    // 如果无法从提交信息中提取真实数据，返回0而不是估算值
    // 这样可以避免显示不准确的数据
    return 0;
  }
  
  /**
   * 生成基于真实提交信息的diff
   */
  private generateCommitDiff(commit: GitCommitInfo): string {
    const lines = [
      `commit ${commit.hash}`,
      `Author: ${commit.author} <${commit.email}>`,
      `Date: ${commit.date.toISOString()}`,
      '',
      `    ${commit.message}`,
      ''
    ];
    
    // 尝试从提交信息中提取更多详细信息
    const files = this.extractFilesFromCommitMessage(commit.message);
    if (files.length > 0) {
      lines.push('Files changed:');
      files.forEach(file => {
        const additions = this.extractStatsFromMessage(commit.message, 'additions');
        const deletions = this.extractStatsFromMessage(commit.message, 'deletions');
        const stats = [];
        if (additions > 0) stats.push(`+${additions}`);
        if (deletions > 0) stats.push(`-${deletions}`);
        const statsStr = stats.length > 0 ? ` (${stats.join(', ')})` : '';
        lines.push(`    ${file}${statsStr}`);
      });
      lines.push('');
    }
    
    lines.push('Note: This diff is generated from commit information.');
    lines.push('Detailed file changes are not available in browser environment.');
    
    return lines.join('\n');
  }

  /**
   * 生成示例diff（基于提交信息）
   */
  private generateSampleDiff(content: string, commitMessage: string): string {
    const lines = content.split('\n').slice(0, 10); // 取前10行作为示例
    const diffLines: string[] = [];
    
    diffLines.push(`@@ 提交信息: ${commitMessage} @@`);
    diffLines.push('');
    
    // 添加一些示例变更行
    for (let i = 0; i < Math.min(5, lines.length); i++) {
      if (i % 2 === 0) {
        diffLines.push(`  ${lines[i]}`);
      } else {
        diffLines.push(`- ${lines[i]}`);
        diffLines.push(`+ ${lines[i]} // 修改内容`);
      }
    }
    
    diffLines.push('');
    diffLines.push('注意: 由于浏览器环境限制，这是基于当前文件内容生成的示例差异。');
    
    return diffLines.join('\n');
  }

  /**
   * 获取Git用户信息
   */
  async getGitUserInfo(): Promise<{ name: string; email: string } | null> {
    try {
      if (!this.gitDirectoryHandle) {
        return null;
      }
      
      // 尝试读取 .git/config 文件
      const configFile = await this.gitDirectoryHandle.getFileHandle('config');
      const file = await configFile.getFile();
      const content = await file.text();
      
      // 解析Git配置文件中的用户信息
      const nameMatch = content.match(/\[user\][\s\S]*?name\s*=\s*(.+?)(?:\n|$)/i);
      const emailMatch = content.match(/\[user\][\s\S]*?email\s*=\s*(.+?)(?:\n|$)/i);
      
      const name = nameMatch ? nameMatch[1].trim().replace(/["']/g, '') : '';
      const email = emailMatch ? emailMatch[1].trim().replace(/["']/g, '') : '';
      
      return name || email ? { name, email } : null;
    } catch (error) {
      console.warn('无法读取Git用户信息:', error);
      return null;
    }
  }

  /**
   * 获取当前分支名
   */
  async getCurrentBranch(): Promise<string> {
    try {
      if (!this.gitDirectoryHandle) {
        return 'main';
      }
      
      // 读取 .git/HEAD 文件
      const headFile = await this.gitDirectoryHandle.getFileHandle('HEAD');
      const file = await headFile.getFile();
      const content = await file.text();
      
      // 解析分支名
      const match = content.match(/ref: refs\/heads\/(.+)/);
      return match ? match[1].trim() : 'main';
    } catch {
      return 'main';
    }
  }

  /**
   * 获取仓库状态
   */
  async getRepositoryStatus(): Promise<{
    clean: boolean;
    ahead: number;
    behind: number;
  }> {
    // 在浏览器环境中无法获取详细的仓库状态
    return {
      clean: true,
      ahead: 0,
      behind: 0
    };
  }
}